/*
 Copyright (c) 2009, Ivan Popivanov
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:

 * Redistributions of source code must retain the above copyright
 notice, this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright
 notice, this list of conditions and the following disclaimer in the
 documentation and/or other materials provided with the distribution.

 * Neither the name of StockCandles nor the names of its contributors
 may be used to endorse or promote products derived from this software
 without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "Csv.h"

#define SUBMIT_FIELD \
   if(!quoted) entryPos -= numSpaces;  \
   entry[entryPos] = '\0';   \
   fields.push_back(entry);   \
   state = FieldNotBegun;  \
   entryPos = 0;  \
   numSpaces = 0; \
   quoted = false;

bool
Csv::parse(const char *line, QStringList &fields)
{
   Q_ASSERT(line != NULL);
   int len = strlen(line);

   QByteArray entry;
   entry.resize(len + 1);

   int state = FieldNotBegun;
   int entryPos = 0;

   int numSpaces = 0;

   bool quoted = false;

   char c;
   int pos = 0;

   // Process everything, including the terminator
   while(pos <= len)
   {
      c = line[pos++];

      Q_ASSERT(c != '\n' && c != '\r');
      switch(state)
      {
      case FieldNotBegun:
         if(isSpace(c))
         {
            continue;
         }
         else if(isTerm(c))
         {
         }
         else if(isDelim(c))
         {
            // Comma
            SUBMIT_FIELD;
         }
         else if(isQuote(c))
         {
            // Quote
            state = FieldBegun;
            quoted = 1;
         }
         else
         {
            // Anything else
            state = FieldBegun;
            quoted = 0;
            entry[entryPos++] = c;
         }
         break;

      case FieldBegun:
         if(isQuote(c))
         {
            // Quote
            if(quoted)
            {
               entry[entryPos++] = c;
               state = FieldMightHaveEnded;
            }
            else
            {
               // STRICT ERROR - double quote inside non-quoted field
               if(flags.testFlag(CsvFile::Strict)) return false;
               entry[entryPos++] = c;
               numSpaces = 0;
            }
         }
         else if(isTerm(c))
         {
            SUBMIT_FIELD;
         }
         else if(isDelim(c))
         {
            // Comma
            if(quoted) entry[entryPos++] = c;
            else SUBMIT_FIELD;
         }
         else if(!quoted && isSpace(c))
         {
            // Tab or space for non-quoted field
            entry[entryPos++] = c;
            ++numSpaces;
         }
         else
         {
            // Anything else
            entry[entryPos++] = c;
            numSpaces = 0;
         }
         break;

      case FieldMightHaveEnded:
         // This only happens when a quote character is encountered in a quoted field
         if(isDelim(c))
         {
            // Comma
            entryPos -= numSpaces + 1; // get rid of spaces and original quote
            SUBMIT_FIELD;
         }
         else if(isTerm(c))
         {
            entryPos -= numSpaces + 1;
            SUBMIT_FIELD;
         }
         else if (isSpace(c))
         {
            // Space or Tab
            entry[entryPos++] = c;
            numSpaces++;
         }
         else if(isQuote(c))
         {
            // Quote
            if(numSpaces > 0)
            {
               // STRICT ERROR - unescaped double quote
               if(flags.testFlag(CsvFile::Strict)) return false;
               numSpaces = 0;
               entry[entryPos++] = c;
            }
            else
            {
               // Two quotes in a row
               state = FieldBegun;
            }
         }
         else
         {
            // Anything else
            // STRICT ERROR - unescaped double quote
            if(flags.testFlag(CsvFile::Strict)) return false;
            state = FieldBegun;
            numSpaces = 0;
            entry[entryPos++] = c;
         }
         break;
      }
   }

   return true;
}

CsvFile::CsvFile(const QString &path)
       : file(path)
{
}

bool
CsvFile::readLine(QStringList &values)
{
   static char line[MaxLine];
   qint64 err = file.readLine(line, sizeof(line));
   if(err <= 0) return false;

   int last = err - 1;
   while(last >= 0 && (line[last] == '\n' || line[last] == '\r'))
   {
      line[last--] = '\0';
   }
   if(last == 0) return false;

   values.clear();

   // Parse the line
   if(!parse(line, values))
   {
      values.clear();
   }
   return true;
}

bool
CsvFile::writeLine(const QStringList &values)
{
   QByteArray bytes;
   QStringListIterator iter(values);
   while(iter.hasNext())
   {
      if(iter.hasPrevious()) bytes.append(',');
      bytes.append(iter.next().toAscii());
   }
   return writeLine(bytes);
}

bool
CsvFile::writeLine(const QByteArray &s)
{
   if(s.length() != file.write(s)) return false;
   return 1 == file.write("\n");
}